<template>
  <view class="main-menu">
    <view class="title">推箱子</view>
    
    <view class="menu-buttons">
      <button class="menu-btn" @tap="handleMainBtn">{{ mainBtnText }}</button>
      <button class="menu-btn" @tap="handleSelectLevel">选择关卡</button>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import './index.scss'

// 跨端存储读取
function getStorageSync(key) {
  if (Taro.getStorageSync && typeof Taro.getStorageSync === 'function') {
    return Taro.getStorageSync(key)
  } else if (typeof window !== 'undefined' && window.localStorage) {
    return window.localStorage.getItem(key)
  }
  return null
}

export default {
  setup() {
    // 是否有存档
    const hasSave = ref(false)
    const savedLevel = ref(1)

    onMounted(() => {
      const level = getStorageSync('currentLevel')
      if (level) {
        hasSave.value = true
        savedLevel.value = level
      } else {
        hasSave.value = false
        savedLevel.value = 1
      }
    })

    // 按钮文本
    const mainBtnText = computed(() => hasSave.value ? '继续游戏' : '新游戏')

    // 主按钮点击
    const handleMainBtn = () => {
      const level = hasSave.value ? savedLevel.value : 1
      Taro.navigateTo({
        url: `/pages/game/game?level=${level}`
      })
    }

    // 选择关卡
    const handleSelectLevel = () => {
      Taro.navigateTo({
        url: '/pages/level-select/level-select'
      })
    }

    return {
      mainBtnText,
      handleMainBtn,
      handleSelectLevel
    }
  }
}
</script>
